package com.nowcoder.community.config;

import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author cjh
 * @date 2023/2/5 - 9:44
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter implements CommunityConstant {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        授权
        http.authorizeRequests()
                .antMatchers(
                        "/user/setting",
                        "user/upload",
                        "/discuss/add",
                        "/comment/add/**",
                        "/letter/**",
                        "/notice/**",
                        "/like",
                        "/follow",
                        "/unfollow"
                )
                .hasAnyAuthority(
                        AUTHORITY_USER, AUTHORITY_ADMIN, AUTHORITY_MODERATOR
                )
                .antMatchers(
                        "/discuss/top",
                        "/discuss/wonderful"
                ).hasAnyAuthority(
                        AUTHORITY_MODERATOR
                )
                .antMatchers(
                        "/discuss/delete",
                        "/data/**"
                ).hasAnyAuthority(
                        AUTHORITY_ADMIN
                )
//                其他的任何请求就都放过
                .anyRequest().permitAll()
//                禁用csrf
                .and().csrf().disable();

//        权限不够时 的处理
        http.exceptionHandling()
//                没登陆 需要认证时的处理
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
//                        异步还是同步
                        String header = request.getHeader("x-requested-with");
//                        异步
                        if ("XMLHttpRequest".equals(header)) {

                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommunityUtil.getJsonString(403, "没有登陆"));

                        } else {
                            response.sendRedirect(request.getContextPath() + "/login");
                        }
                    }
                })
//                权限不足时
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {

                        //                        异步还是同步
                        String header = request.getHeader("x-requested-with");
//                        异步
                        if ("XMLHttpRequest".equals(header)) {

                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommunityUtil.getJsonString(403, "没有访问此功能权限"));

                        } else {
                            response.sendRedirect(request.getContextPath() + "/denied");
                        }
                    }
                });
//        security底层默认会拦截/logout请求 进行推出请求
//        覆盖它默认的逻辑 才能执行我们自己的退出代码
//        这样 security就去拦截下面这个退出路径了  但是其实我们退出时就是普通的/logout
        http.logout().logoutUrl("/securitylogout");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resource/**");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
    }
}
